import random
import os.path


def show():
    quiz=request.args(0)
    quiz_id=request.args(1)
    if quiz=='personal':
        content=db(db.quizpersonal.id==quiz_id).select().first()
    elif quiz=='regional':
        content=db(db.quizregional.id==quiz_id).select().first()
    else:
        content=False
    if content:
        return dict(content=content)
    else:
        redirect(URL('quiz', 'group', args=request.args(1)))
        
        
def personal():
    memberships = db(db.auth_membership.user_id==auth.user_id)._select(db.auth_membership.group_id) or redirect(URL('index'))
    row = db((db.auth_group.id.belongs(memberships)) & (db.auth_group.id==request.args(0)) & (~db.auth_group.role.contains(['user_', 'admins'], all=False))).select(db.auth_group.ALL, db.stats.ALL, orderby=~db.stats.total, left=db.stats.on(db.auth_group.id==db.stats.group_id)).first() or redirect(URL('index'))

    #starten van sessie
    if not session.quizNavigator:
        session.quizNavigator = dict(type='random', list=[], group=request.args(0)) 
    
    served_content=session.quizNavigator["list"]
    question=db((db.quizpersonal.group_id==request.args(0)) & (~db.quizpersonal.id.belongs(served_content))).select(orderby='<random>').first()          
    if db((db.quizpersonal.group_id==request.args(0)) & (~db.quizpersonal.id.belongs(served_content))).isempty():
        #Clear served_content
        del session.quizNavigator
        redirect(URL('quiz', 'group', args=request.args(0)))
    session.quizNavigator["list"].append(question.id)    
    quiz_id=question.id
    quiz_type="personal"
    return dict(quiz_id=quiz_id,quiz_type=quiz_type)

def regional():
    memberships = db(db.auth_membership.user_id==auth.user_id)._select(db.auth_membership.group_id) or redirect(URL('index'))
    row = db((db.auth_group.id.belongs(memberships)) & (db.auth_group.id==request.args(0)) & (~db.auth_group.role.contains(['user_', 'admins'], all=False))).select(db.auth_group.ALL, db.stats.ALL, orderby=~db.stats.total, left=db.stats.on(db.auth_group.id==db.stats.group_id)).first() or redirect(URL('index'))

    #starten van sessie
    if not session.quizNavigator:
        session.quizNavigator = dict(type='random', list=[], group=request.args(0)) 
    
    served_content=session.quizNavigator["list"]
    question=db((db.quizregional.group_id==request.args(0)) & (~db.quizregional.id.belongs(served_content))).select(orderby='<random>').first()          
    if db((db.quizregional.group_id==request.args(0)) & (~db.quizregional.id.belongs(served_content))).isempty():
        #Clear served_content
        del session.quizNavigator
        redirect(URL('quiz', 'group', args=request.args(0)))
    session.quizNavigator["list"].append(question.id)    
    quiz_id=question.id
    quiz_type="regional"
    response.view='emulator/personal.html'
    return dict(quiz_id=quiz_id,quiz_type=quiz_type)